package io.spring.nn.controller;

import io.spring.nn.bean.Image;
import io.spring.nn.bean.User;
import io.spring.nn.mapper.ImageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.sql.Date;
import java.util.List;

@Controller
public class UploadController {


    @Autowired
    ImageMapper imageMapper;


    @GetMapping("/upload")
    public String upload() {
        return "upload";
    }

    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file,
                         HttpSession session) {
        if (file.isEmpty()) {
//            return "上传失败，请选择文件";
            return "photo";
        }

        String fileName = file.getOriginalFilename();
        String filePath = ClassUtils.getDefaultClassLoader().getResource("").getPath();
        String[] pathList = filePath.split("/target/");
        filePath = pathList[0] + "/src/main/resources/static/images/";

        User user = (User) session.getAttribute("user");
        String sqlImagePath = "/images/";
        imageMapper.insertImage(sqlImagePath + fileName, user.getId());
        System.out.println();
        File dest = new File(filePath + fileName);
        try {
            file.transferTo(dest);
            return "redirect:/photo";
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "error";
    }

    @GetMapping("/photo")
    public String getAllPhoto(HttpSession session,
                              Model model) {

        User user = (User) session.getAttribute("user");

        List<Image> allPhoto = imageMapper.getAllPhoto(user.getId());

        session.setAttribute("photoPath", allPhoto);

        return "photo";
    }


}



